package cn.uncode.rpc.transport.support;

import java.net.InetSocketAddress;

import cn.uncode.rpc.common.ChannelState;
import cn.uncode.rpc.common.log.Logger;
import cn.uncode.rpc.common.log.LoggerFactory;
import cn.uncode.rpc.core.Request;
import cn.uncode.rpc.core.URL;
import cn.uncode.rpc.core.URLParam;
import cn.uncode.rpc.exception.TransportException;
import cn.uncode.rpc.spi.ExtensionLoader;
import cn.uncode.rpc.transport.Client;
import cn.uncode.rpc.transport.Codec;
import cn.uncode.rpc.util.FrameworkUtil;



public abstract class AbstractClient implements Client {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(AbstractClient.class);

    protected InetSocketAddress localAddress;
    protected InetSocketAddress remoteAddress;

    protected URL url;
    protected Codec codec;

    protected volatile ChannelState state = ChannelState.UNINIT;

    public AbstractClient(URL url) {
        this.url = url;
		this.codec = ExtensionLoader.getExtensionLoader(Codec.class)
				.getExtension(url.getParameter(URLParam.CODEC.getName(), URLParam.CODEC.getValue()));
        LOGGER.info("init nettyclient. url:" + url.getHost() + "-" + url.getPath() + ", use codec:" + codec.getClass().getSimpleName());
    }

    @Override
    public InetSocketAddress getLocalAddress() {
        return localAddress;
    }

    @Override
    public InetSocketAddress getRemoteAddress() {
        return remoteAddress;
    }

    @Override
    public void heartbeat(Request request) {
        throw new TransportException("heartbeat not support: " + FrameworkUtil.toString(request));
    }

    public void setLocalAddress(InetSocketAddress localAddress) {
        this.localAddress = localAddress;
    }

    public void setRemoteAddress(InetSocketAddress remoteAddress) {
        this.remoteAddress = remoteAddress;
    }
}
